package com.gcy.wanandroid.base.viewmodel;

import android.content.res.Resources;

import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.gcy.wanandroid.config.App;
import com.gcy.wanandroid.config.LoadState;
import com.gcy.wanandroid.http.data.HttpDisposable;
import com.gcy.wanandroid.http.request.HttpFactory;
import com.gcy.wanandroid.http.request.HttpRequest;

/**
 * @author: gcy
 * @description: ViewModel基类
 * @version: 1.0
 * @CreateTime: 2023-05-15  12:01
 */
public abstract class BaseViewModel extends ViewModel implements DefaultLifecycleObserver {

    public Resources resources;

    //收藏文章
    public MutableLiveData<Object> collect = new MutableLiveData<>();
    //加载状态
    public MutableLiveData<LoadState> loadState = new MutableLiveData<>();
    //加载错误信息
    public MutableLiveData<String> errorMsg = new MutableLiveData<>("加载出错");
    //是否为刷新数据
    public boolean mRefresh;
    //重新加载数据，没有网络，点击重试时回调
    public void reloadData() {

    }

    public Resources getResources() {
        if (resources == null) {
            resources = App.getContext().getResources();
        }
        return resources;
    }

    //收藏文章
    private void collectArticle(int id) {
        HttpRequest.getInstance()
                .collectArticle(id)
                .compose(HttpFactory.schedulers())
                .subscribe(new HttpDisposable<Object>() {
                    @Override
                    public void success(Object mArticleListBean) {
                        collect.postValue(mArticleListBean);
                    }

                    public void onError(Throwable e) {
                        collect.postValue(null);
                    }
                });

    }

    //取消收藏文章
    private void unCollectArticle(int id) {
        HttpRequest.getInstance()
                .unCollectArticle(id)
                .compose(HttpFactory.schedulers())
                .subscribe(new HttpDisposable<Object>() {
                    @Override
                    public void success(Object mArticleListBean) {
                        collect.postValue(mArticleListBean);
                    }
                });
    }

    //改变文章收藏状态
    public void changeArticleCollect(boolean collect, int id) {
        if (collect) {
            collectArticle(id);
        } else {
            unCollectArticle(id);
        }
    }

    //获取文章收藏状态
    public LiveData<Object> getCollectStatus() {
        return collect;
    }

}
